<?php

namespace Yjius\common;
/**
 * 常用工具应用类方法
 * Class ToolsHelper
 * @package YJiusCommonHelper
 * @date  2021/11/30 16:43
 */
class ToolsHelper
{
    /**
     * Purpose: 直接远程下载附件
     * Author:yingjiusheng@gsdata.cn
     * @date 2022/6/16 17:49
     */
    public static function downloadFileUrl($fileUrl)
    {
        $pathInfo = pathinfo($fileUrl);
        // $url就是文件的全路径 注意是全路径 get_headers函数会打印出oss文件的详细信息
        $info = get_headers($fileUrl, true);
        $fileName = $pathInfo['basename'];
        $size = $info['Content-Length'];
        header("Content-type:application/octet-stream");
        header("Content-Disposition:attachment;filename = " . $fileName);
        header("Accept-ranges:bytes");
        header("Accept-length:" . $size);
        ob_clean();
        flush();
        readfile($fileUrl);
        die();
    }

    /**
     * 阿拉伯数字转中文数字
     * 可读中文，可读金额
     * @param $num
     * @return string
     */
    public static function formatNumberToWord($num)
    {
        $chiNum = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
        $chiUni = array('', '拾', '佰', '仟', '万', '亿', '拾', '佰', '仟');
        $num_str = (string)$num;
        $count = strlen($num_str);
        $last_flag = true; //上一个 是否为0
        $zero_flag = true; //是否第一个
        $temp_num = null; //临时数字
        $chiStr = '';//拼接结果
        if ($count == 2) {//两位数
            $temp_num = $num_str[0];
            $chiStr = $temp_num == 1 ? $chiUni[1] : $chiNum[$temp_num] . $chiUni[1];
            $temp_num = $num_str[1];
            $chiStr .= $temp_num == 0 ? '' : $chiNum[$temp_num];
        } else if ($count > 2) {
            $index = 0;
            for ($i = $count - 1; $i >= 0; $i--) {
                $temp_num = $num_str[$i];
                if ($temp_num == 0) {
                    if (!$zero_flag && !$last_flag) {
                        $chiStr = $chiNum[$temp_num] . $chiStr;
                        $last_flag = true;
                    }
                } else {
                    $chiStr = $chiNum[$temp_num] . $chiUni[$index % 9] . $chiStr;
                    $zero_flag = false;
                    $last_flag = false;
                }
                $index++;
            }
        } else {
            $chiStr = $chiNum[$num_str[0]];
        }
        return $chiStr;
    }

    /**
     * 截取手机号中间四位
     * 可传入座机号如：05516625654 或 0551-6625654亦可
     *
     * @return: mixed
     * @date  :2016/8/16
     * @author: yingjs
     */
    public static function hidTel($phone)
    {
        $IsWhat = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i', $phone); //固定电话
        if ($IsWhat == 1) {
            return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i', '$1****$2', $phone);
        } else {
            return preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $phone);
        }
    }

    /**
     * 身份证隐藏生日四位信息
     *
     * @return: mixed|string
     * @date  :2016/8/16
     * @author: yingjs
     */
    public static function hidIdCard($idCard)
    {
        return strlen($idCard) == 15 ? substr_replace($idCard, "******", 8, 6) : (strlen($idCard) == 18 ? substr_replace($idCard, "******", 10, 6) : "提示身份证位数不正常！");
    }

    /**
     * Purpose: 下划线的数据和驼峰的数据互转
     * 递归转
     * Author:yingjiusheng@gsdata.cn
     * @date 2022/5/20 16:19
     */
    public static function humpUnderlineConversion($params, $type = 1)
    {
        $newArr = [];
        if (!is_array($params) || empty($params)) return $newArr;
        foreach ($params as $key => $val) {
            if ($type == 1) {
                $newkey = preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {
                    return strtoupper($matches[2]);
                }, $key);
            } else {
                $newkey = $key;
                if (!strstr($key, '_')) {
                    $key = str_replace("_", "", $key);
                    $key = preg_replace_callback('/([A-Z]{1})/', function ($matches) {
                        return '_' . strtolower($matches[0]);
                    }, $key);
                    $newkey = ltrim($key, "_");
                }
            }

            $newArr[$newkey] = is_array($val) ? self::humpUnderlineConversion($val, $type) : $val;
        }
        return $newArr;
    }

    /**
     * Purpose: 生成一个uuid
     * @date 2021/11/30 16:20
     */
    public static function getUuid()
    {
        if (function_exists('com_create_guid')) {
            return com_create_guid();
        } else {
            mt_srand((double)microtime() * 10000);
            $charid = md5(uniqid(rand(), true));
            $hyphen = chr(45); // "-"
            $uuid = substr($charid, 0, 8) . $hyphen
                . substr($charid, 8, 4) . $hyphen
                . substr($charid, 12, 4) . $hyphen
                . substr($charid, 16, 4) . $hyphen
                . substr($charid, 20, 12);
            return $uuid;
        }
    }

    /**
     * 生成随机数
     * @param integer $count
     * @param string $addchars
     * @param boolean $arrayOut
     * @param boolean $unique
     * @return mixed
     */
    public static function random($count = 6, $addchars = '', $arrayOut = FALSE, $unique = FALSE)
    {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addchars;
        $tmp = range(0, strlen($chars) - 1);

        if ($unique === TRUE) {
            shuffle($tmp);
            $keys = array_slice($tmp, 0, $count);
        } else {
            $keys = array_rand($tmp, $count);
        }

        $random = array();

        foreach ($keys as $value) {
            $random[] = $chars[$value];
        }

        if ($arrayOut === TRUE) {
            return $random;
        } else {
            return implode('', $random);
        }
    }

    /**
     * * PHP截取UTF-8字符串，解决半字符问题。
     * 截取utf-8字符串，截取后，用 ...代替被截取的部分
     * $length 左边的子串的长度
     * 按字符截取
     *
     * @param     $string
     * @param int $length
     * @return string
     */
    public static function cutStr($string, $length = 43)
    {
        $wordscut = '';
        $j = 0;
        preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $string, $info);

        for ($i = 0; $i < count($info[0]); $i++) {
            $wordscut .= $info[0][$i];
            $j = ord($info[0][$i]) > 127 ? $j + 2 : $j + 1;

            if ($j > $length - 3) {
                return $wordscut . " ...";
            }
        }
        return join('', $info[0]);
    }

    /**
     * 中文截取，支持gb2312,gbk,utf-8,big5
     *
     * @param string $str 要截取的字串
     * @param int $start 截取起始位置
     * @param int $length 截取长度
     * @param string $charset utf-8¦gb2312¦gbk¦big5 编码
     * @param        $suffix  尾缀
     */
    public static function subString($str, $length = -1, $start = 0, $suffix = NULL, $charset = "")
    {
        if ($length < 1) {
            return $str;
        }

        if ($str == NULL || empty($str)) {
            return '';
        }

        if (empty($charset)) {
            $charset = 'utf-8';
        }

        if (function_exists('mb_substr')) {
            if (mb_strlen($str, $charset) <= $length) {
                return $str;
            }

            $slice = mb_substr($str, $start, $length, $charset);
        } else {
            $re['utf-8'] = "/[\x01-\x7f]¦[\xc2-\xdf][\x80-\xbf]¦[\xe0-\xef][\x80-\xbf]{2}¦[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]¦[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk'] = "/[\x01-\x7f]¦[\x81-\xfe][\x40-\xfe]/";
            $re['big5'] = "/[\x01-\x7f]¦[\x81-\xfe]([\x40-\x7e]¦\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);

            if (count($match[0]) <= $length) {
                return $str;
            }

            $slice = join("", array_slice($match[0], $start, $length));
        }

        if (!empty($suffix) && is_string($suffix)) {
            return $slice . $suffix;
        }

        return $slice;
    }


    /**
     * 将字节转换为可读文本
     * @param int $size 大小
     * @param string $delimiter 分隔符
     * @param int $precision 小数位数
     * @return string
     */
    public static function formatBytes($size, $delimiter = '', $precision = 2)
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, $precision) . $delimiter . $units[$i];
    }

    /**
     * Purpose: 根据问题列表生成num套试卷
     * Author:yingjiusheng@gsdata.cn
     * @date 2021/7/20 16:56
     *
     * [0] => Array
     * (
     * [practiceId] => 3
     * [question] => 天空是什么颜色的？
     * [options] => Array
     * (
     * [0] => Array
     * (
     * [text] => 黑色
     * [flag] => 0
     * )
     *
     * [1] => Array
     * (
     * [text] => 红色
     * [flag] => 0
     * )
     *
     * [2] => Array
     * (
     * [text] => 蓝色
     * [flag] => 1
     * )
     *
     * [3] => Array
     * (
     * [text] => 绿色
     * [flag] => 0
     * )
     * )
     * )
     *
     * [1] => Array
     * (
     * [practiceId] => 4
     * [question] => 大海是什么颜色的？
     * [options] => Array
     * (
     * [0] => Array
     * (
     * [text] => 黑色
     * [flag] => 0
     * )
     *
     * [1] => Array
     * (
     * [text] => 红色
     * [flag] => 0
     * )
     *
     * [2] => Array
     * (
     * [text] => 绿色
     * [flag] => 0
     * )
     *
     * [3] => Array
     * (
     * [text] => 蓝色
     * [flag] => 1
     * )
     *
     * )
     *
     * )
     * $num  生成n套试卷
     * $randomOption 选项答案是否随机
     * $newOptions 是否自动生成新选项
     */
    public static function generatePager($data, $num = 3, $randomOption = 0, $newOptions = 1)
    {
        $res = [];
        for ($i = 1; $i <= $num; $i++) {
            shuffle($data);
            if (!empty($data)) {
                foreach ($data as &$val) {
                    if (!empty($randomOption)) {
                        shuffle($val['options']);
                    }
                    if (!empty($newOptions)) {
                        $val['optionsNew']['a'] = '';
                        $kk = 'A';
                        foreach ($val['options'] as $k => $v) {
                            $val['optionsNew']['q'][$kk] = $v['text'];
                            if (!empty($v['flag'])) {
                                $val['optionsNew']['a'] .= $kk . ',';
                            }
                            $kk++;
                        }
                        $val['optionsNew']['a'] = substr($val['optionsNew']['a'], 0, -1);
                    }
                }
            }
            $res[$i] = $data;
        }
        return $res;
    }

    /**
     * 获得访客真实ip
     *
     * @return mixed
     */
    public static function getIpAddr()
    {
        $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';

        if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])
            && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
            foreach ($matches[0] as $xip) {
                if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                    $ip = $xip;
                    break;
                }
            }
        }

        return $ip;
    }

    /**
     * 获得访客浏览器类型
     *
     * @return string
     */
    public static function getBrowser()
    {
        if (!empty($_SERVER['HTTP_USER_AGENT'])) {
            $browser = $_SERVER['HTTP_USER_AGENT'];

            if (preg_match('/MSIE/i', $browser)) {
                $browser = 'MSIE';
            } elseif (preg_match('/Firefox/i', $browser)) {
                $browser = 'Firefox';
            } elseif (preg_match('/Chrome/i', $browser)) {
                $browser = 'Chrome';
            } elseif (preg_match('/Safari/i', $browser)) {
                $browser = 'Safari';
            } elseif (preg_match('/Opera/i', $browser)) {
                $browser = 'Opera';
            } else {
                $browser = 'Other';
            }

            return $browser;
        } else {
            return "unknow";
        }
    }

    /**
     * 获取访客操作系统
     *
     * @return string
     */
    public static function getOs()
    {
        if (!empty($_SERVER['HTTP_USER_AGENT'])) {
            $OS = $_SERVER['HTTP_USER_AGENT'];

            if (preg_match('/win/i', $OS)) {
                $OS = 'Windows';
            } elseif (preg_match('/Mac/i', $OS)) {
                $OS = 'MAC';
            } elseif (preg_match('/linux/i', $OS)) {
                $OS = 'Linux';
            } elseif (preg_match('/unix/i', $OS)) {
                $OS = 'Unix';
            } elseif (preg_match('/bsd/i', $OS)) {
                $OS = 'BSD';
            } else {
                $OS = 'Other';
            }

            return $OS;
        } else {
            return "unknow";
        }
    }
}